package com.monitor.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.monitor.entity.*;
import com.monitor.service.*;
import com.monitor.util.ReadExcel;
import com.monitor.util.Result;
import com.monitor.util.WDWUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 物料报废表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-12
 */
@RestController
@RequestMapping("/erpScrapTire")
@Api(description="物料报废表")
public class ErpScrapTireController {
    @Resource
    private ErpScrapTireService tireService;
    @Resource
    private ErpCustomerService customerService;
    @Resource
    private ErpMaterielService materielService;
    @Resource
    private ErpWarehouseService warehouseService;
    @Resource
    private ErpMaterielFlowMaterielService flowMaterielService;
    @Resource
    private ErpCustomerWarehouseService customerWarehouseService;

    @Value("${web.upload-path}")
    private String path;

    /**
     * 上传Excel,读取Excel中内容
     * @param file
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/inertTireDate")
    @ApiOperation("插入物料保费信息")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<Integer> inertTireDate(@RequestParam(value="file") MultipartFile file,
                                  HttpServletRequest request, HttpServletResponse response,Integer custId) {
        Result<Integer> result=new Result<Integer>();
        try{
            ErpCustomer customer=customerService.selectById(custId);
            List<ErpCustomer> customers=customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_service_com",customer.getCusCode()));
            customers.add(customer);
            List<Integer> sustIds=customers.stream().map(ErpCustomer::getId).collect(Collectors.toList());
            List<ErpWarehouse> warehouses=warehouseService.selectBatchIds(sustIds);
            List<Integer> wareIds=warehouses.stream().distinct().map(ErpWarehouse::getId).collect(Collectors.toList());

            String Msg =null;
            boolean b = false;

            //判断文件是否为空
            if(file==null){
                result.setCount(0);
                result.setCode(1);
                result.setData(null);
                result.setMsg("文件是为空！");
                return result;
            }

            //获取文件名
            String name=file.getOriginalFilename();

            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
            long size=file.getSize();
            if(name==null || ("").equals(name) && size==0 && !WDWUtil.validateExcel(name)){
                result.setCount(0);
                result.setCode(1);
                result.setData(null);
                result.setMsg("文件格式不正确！请使用.xls或.xlsx后缀文档。");
                return result;
            }

            //创建处理EXCEL
            ReadExcel readExcel=new ReadExcel();
            //解析excel，获取客户信息集合。
            List<List<Object>> customerList = readExcel.getExcelInfo(path,file,request);
            if(customerList != null && !customerList.toString().equals("[]") && customerList.size()>=1){
                b = true;
            }
            //List<ErpScrapTire> tires=new ArrayList<ErpScrapTire>();
            List<ErpWarehouse> warehouses1=new ArrayList<ErpWarehouse>();
            List<ErpScrapTire> tires=new ArrayList<ErpScrapTire>();
            if(b){
                //迭代添加客户信息（注：实际上这里也可以直接将customerList集合作为参数，在Mybatis的相应映射文件中使用foreach标签进行批量添加。）
                for(List<Object> object:customerList){
                    //这里可以做添加数据库的功能
                    //tires.add(tireService.listToObject(object));
                    ErpScrapTire tire= tireService.listToObject(object);
                    String scrProduceid=tire.getScrProduceid();
                    ErpMateriel materiel=materielService.selectOne(new EntityWrapper<ErpMateriel>().eq("materiel_production_id",scrProduceid).and().in("warehouse_id",wareIds));
                    if(null==materiel){
                        tires.add(tire);
                        continue;
                    }

                    ErpWarehouse warehouse=warehouseService.selectOne(new EntityWrapper<ErpWarehouse>().eq("materiel_id",materiel.getMaterielId()).and().eq("warehouse_id",materiel.getWarehouseId()));
                    warehouse.setMaterielNumber(warehouse.getMaterielOccupyNumber()-1);
                    warehouses1.add(warehouse);
                    tire.setCustomerId(warehouse.getCustomerId());
                    tires.add(tire);
                }
                if(0!=warehouses1.size()){
                    warehouseService.updateAllColumnBatchById(warehouses1);
                }
                tireService.insertBatch(tires);
                Msg ="批量导入EXCEL成功！";
                result.setMsg(Msg);
            }else{
                Msg ="批量导入EXCEL失败！";
                result.setMsg(Msg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/getScrapTirePageBycustId")
    @ApiOperation("根据客户ID查询物料报废分页")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<Page<ErpScrapTire>> getScrapTirePageBycustId(@RequestParam(value = "page", defaultValue = "1") int page,
                                                  @RequestParam(value="limit",defaultValue="10") int limit, Integer custId) {
        Result<Page<ErpScrapTire>> result=new Result<Page<ErpScrapTire>>();
        try{
            Page<ErpScrapTire> page1=new Page<ErpScrapTire>(page,limit);
            String custIdsStd=customerService.getcustOfMe(custId);
            Page<ErpScrapTire> carPage=tireService.selectPage(page1,new EntityWrapper<ErpScrapTire>().in("customer_id",custIdsStd));
            //Page<ErpCustomerCar> page=new Page<ErpCustomerCar>(1,2);
            result.setCount(carPage.getRecords().size());
            result.setData(carPage);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }
  @RequestMapping("/getWLKCWLMX")
    @ApiOperation("物料库存,-物料明细")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpScrapTire>> getWLKCWLMX(Integer number) {
      Result<List<ErpScrapTire>>  result=new Result<>();
        try{


            List<ErpScrapTire> erpScrapTires = tireService.selectList(new EntityWrapper<ErpScrapTire>());
       a:     for (int i = 0; i < erpScrapTires.size(); i++) {
                ErpScrapTire erpScrapTire =  erpScrapTires.get(i);
                if (number==0){
                    erpScrapTires.clear();
            break a;
                }else if (erpScrapTires.size()<number){
                    erpScrapTires.add(erpScrapTire);
                }else  if (erpScrapTires.size()==number){
                    break a;
                }else if (number==1){
                    int a=erpScrapTires.size()-1;
                b: while (true){
                if (erpScrapTires.size()!=1){
                    erpScrapTires.remove(a--);
                }else if (number==1&&erpScrapTires.size()==1){

//                    erpScrapTires.remove(1);
                    break b;
                }
                    }
                }else if (erpScrapTires.size()>number){
                    erpScrapTires.remove(erpScrapTire);
                }
            }

            //Page<ErpCustomerCar> page=new Page<ErpCustomerCar>(1,2);

            result.setCount(erpScrapTires.size());
            result.setData(erpScrapTires);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }

    /**
     * 下载Excel模板
     * @param fileName
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/download")
    public String download(String fileName, HttpServletRequest request,
                           HttpServletResponse response) {
        //System.out.println("控制台输出：走入下载");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);
        try {
            /*String path = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath()
                    + "download";//这个download目录为啥建立在classes下的
            */
            InputStream inputStream = new FileInputStream(new File(path+ File.separator + fileName));

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  返回值要注意，要不然就出现下面这句错误！
        //java+getOutputStream() has already been called for this response
        return null;
    }

}

